package fun.coding.leetcode;

public class SortList {

	// Sort a linked list in O(n log n) time using constant space complexity.
	public static void main(String[] args) {
		SortList instance = new SortList();
		int[] a1 = {2, 3, 1, 4};
		ListNode res1 = instance.sortList(LeetCodeHelpers.buildLinkedList(a1));
		LeetCodeHelpers.printList(res1);
	}
	
	// Good one for merge sort.
	public ListNode sortList(ListNode head) {
		if (head == null || head.next == null) return head;
		
		ListNode midNode = findMiddle(head);
		ListNode right = sortList(midNode.next);
		midNode.next = null;
		ListNode left = sortList(head);
		
		ListNode newHead = merge(left, right);
		return newHead;
    }
	
	/**
	 * By convention, 
	 * 1->2->3 mid is 2
	 * 1->2->3->4 mid is 2
	 * so fast should start as next of slow
	 */
	public ListNode findMiddle(ListNode head) {
		if (head == null || head.next == null) return head;
		
		ListNode slow = head;
		ListNode fast = head.next;
		
		while (fast != null && fast.next != null) {
			slow = slow.next;
			fast = fast.next.next;
		}
		return slow;
	}
	
	public ListNode merge(ListNode l1, ListNode l2) {
		ListNode dummy = new ListNode(-1);
		ListNode head = dummy;
		
		while (l1 != null && l2 != null) {
			if (l1.val < l2.val) {
				head.next = l1;
				l1 = l1.next;
			} else {
				head.next = l2;
				l2 = l2.next;
			}
			head = head.next;
		}
		
		if (l1 != null) {
			head.next = l1;
		}
		
		if (l2 != null) {
			head.next = l2;
		}
		
		return dummy.next;
	}
	
}
